<?php
/**
 * 
 * @authors Liujinbi (857053791@QQ.com)
 * @date    2017-10-18 17:16:48
 * @version $Id$
 */
namespace app\finance\controller;

use think\Db;
use think\Controller;
use Godok\Org\Auth;
use think\Config;
use Payinterface\PaySdk;
use think\Log;

class Audit extends Base {
    
    function index(){
    	$param = request()->param();
        $Query = Db::field('ora.*,ogr.rg_id')
        ->table('sdzx_order_refund_audit')->alias('ora')
        ->join('sdzx_order_goods_return ogr','ora.audit_id=ogr.audit_id and ogr.rg_status=1','left')
        ->order('ora.create_time asc')
        ->group('ora.audit_id')
        ->where("(ora.audit_status=0 or ora.audit_status=1)");

        if ($param['keywords']) {
        	$Query->join('sdzx_order o','ora.order_id=o.order_id','left');
        	$Query->where("o.receiver_name like '%{$param['keywords']}%' or o.receiver_mobile like '%{$param['keywords']}%'");
        }

        if (isset($param['status'])) {
        	$Query->where("ora.audit_status={$param['status']}");
        }
        
        $list = $Query->paginate('', false, ['query'=>Request()->param()]);

        $page = $list->render();
        $list = $list->toarray()['data'];
        $return_arr = [];
        foreach ($list as $k => $v) {

            $_time = date('Y-m-d',strtotime($v['create_time']));

            $v['remark'] = str_replace('||', '<br/>', $v['remark']);
            $v['order'] = Db::name('order')->where(['order_id'=>$v['order_id']])->find();
            if (!isset($return_arr[date('Y-m-d',strtotime($v['create_time']))]['time'])) {
                $return_arr[$_time]['time'] = $_time;
                $return_arr[$_time]['count'] = Db::field('sum(ora.money) as money')
                ->table('sdzx_order_refund_audit')->alias('ora')
                ->where("(ora.audit_status=0 or ora.audit_status=1) and ora.create_time like '{$_time}%'")
                ->value('sum(ora.money)');
            }
            
            $return_arr[$_time]['list'][] = $v;

        	// $v['remark'] = str_replace('||', '<br/>', $v['remark']);
        	// $v['order'] = Db::name('order')->where(['order_id'=>$v['order_id']])->find();
        	// $return_arr[] = $v;
        }


        $data['list'] = $return_arr;
        $data['page'] = $page;
        return $this->fetch('',$data);
    }

    /**
     * 审核通过
     * @return [type] [description]
     */
    public function agree()
    {
    	$param = request()->param();
    	!$param['id'] && $this->error('参数错误');

    	$info = Db::name('order_refund_audit')->where(['audit_id'=>$param['id']])->find();
    	if (!in_array($info['audit_status'], [0,1])) { $this->error('本次申请已被处理过，请刷新页面'); }

    	$order = Db::name('order')->where(['order_id'=>$info['order_id']])->find();

    	// 1 : 退货退款审核
		// 2 : 改价退款审核
		// 3 : 订单取消退款
    	switch ($info['audit_type']) {
    		case 1:
    			$this->refundGoods(['audit'=>$info,'order'=>$order]);
    			break;
    		case 2:
    			$this->refundCharge(['audit'=>$info,'order'=>$order]);
    			break;
    		case 3:
    			$this->refundCancel(['audit'=>$info,'order'=>$order]);
    			break;
    		default:
    			$this->error('操作失败');
    			break;
    	}

    }

    /**
     * 退货退款
     * @param  [type] $opt [description]
     * @return [type]      [description]
     */
    public function refundGoods($opt)
    {
    	$order = $opt['order'];
    	$audit = $opt['audit'];
    	$arr = [
			'transaction_id' => $order['pay_no'],
			'out_refund_no'  => $audit['audit_id'],
			'total_fee'      => $order['pay_money']*100,
			'refund_fee'     => $audit['money']*100
    	];
        //日志记录
        Log::init(Config::get('log_refund'));
        Log::record('退货退款'.$order['order_id'],'refund');
        Log::record($arr,'refund');

    	$re = $this->refundMoney($arr);
        
        Log::record($re,'refund');
    	if ($re['status']) {
    		//更改退货商品的退款状态
    		Db::name('order_goods_return')->where(['audit_id'=>$audit['audit_id']])->update(['pay_status'=>1,'pay_time'=>date('Y-m-d H:i:s')]);
    		Db::name('order_refund_audit')->where(['audit_id'=>$audit['audit_id']])->update(['audit_status'=>2,'audit_time'=>date('Y-m-d H:i:s')]);

            $this->sendTmp(['receiver_name'=>$order['receiver_name'],'receiver_mobile'=>$order['receiver_mobile'],'price'=>$audit['money'],'reason'=>rtrim($audit['remark'],'||')]);
    		$this->success('操作成功','refresh');
    	}else{
    		$this->error('退款失败，请请重新审核','',$re['msg']);
    	}
    }

    /**
     * 改价退款
     * @param  [type] $opt [description]
     * @return [type]      [description]
     */
    public function refundCharge($opt)
    {
    	$order = $opt['order'];
    	$audit = $opt['audit'];
    	$arr = [
			'transaction_id' => $order['pay_no'],
			'out_refund_no'  => $audit['audit_id'],
			'total_fee'      => $order['pay_money']*100,
			'refund_fee'     => $audit['money']*100
    	];
        //日志记录
        Log::init(Config::get('log_refund'));
        Log::record('改价退款'.$order['order_id'],'refund');
        Log::record($arr,'refund');

    	$re = $this->refundMoney($arr);

        Log::record($re,'refund');
    	if ($re['status']) {
    		// 更新改价记录的退款状态
    		Db::name('order_change')->where(['audit_id'=>$audit['audit_id']])->update(['pay_status'=>1,'pay_time'=>date('Y-m-d H:i:s'),'pay_no'=>$audit['id']]);
    		Db::name('order_refund_audit')->where(['audit_id'=>$audit['audit_id']])->update(['audit_status'=>2,'audit_time'=>date('Y-m-d H:i:s')]);
            $this->sendTmp(['receiver_name'=>$order['receiver_name'],'receiver_mobile'=>$order['receiver_mobile'],'price'=>$audit['money'],'reason'=>rtrim($audit['remark'],'||')]);
    		$this->success('操作成功','refresh');
    	}else{
    		$this->error('退款失败，请请重新审核','',$re['msg']);
    	}
    }

    /**
     * 取消订单退款
     * @param  [type] $opt [description]
     * @return [type]      [description]
     */
    public function refundCancel($opt)
    {
    	$order = $opt['order'];
    	$audit = $opt['audit'];

        //日志记录
        Log::init(Config::get('log_refund'));
                
    	// 查出所有改价表里面需要退款的记录
    	$list = Db::name('order_change')->where(['audit_id'=>$audit['audit_id'],'pay_status'=>0])->select();

        if (sizeof($list)==1) {
            $tmp = array_shift($list);
            if ($tmp['pid']>0) { //补价单退款
                $pc = Db::name('order_change')->where(['change_id'=>$tmp['pid']])->find();
                $arr = [
                    'transaction_id' => $pc['pay_no'],
                    'out_refund_no'  => $audit['audit_id'].'_'.$tmp['change_id'],
                    'total_fee'      => $pc['price']*100,
                    'refund_fee'     => $tmp['price']*-100
                ];
            }else{
                $arr = [
                    'transaction_id' => $order['pay_no'],
                    'out_refund_no'  => $audit['audit_id'].'_'.$tmp['change_id'],
                    'total_fee'      => $order['pay_money']*100,
                    'refund_fee'     => $tmp['price']*-100
                ];
            }
            Log::record('取消退款'.$order['order_id'],'refund');
            Log::record($arr,'refund');

            $re = $this->refundMoney($arr);
            
            Log::record($re,'refund');
            if ($re['status']) {
                // 更新改价记录的退款状态
                Db::name('order_change')->where(['change_id'=>$tmp['change_id']])->update(['pay_status'=>1,'pay_time'=>date('Y-m-d H:i:s'),'pay_no'=>$arr['out_refund_no'],'error'=>null]);
                Db::name('order_refund_audit')->where(['audit_id'=>$audit['audit_id']])->update(['audit_status'=>2,'audit_time'=>date('Y-m-d H:i:s')]);
                $this->sendTmp(['receiver_name'=>$order['receiver_name'],'receiver_mobile'=>$order['receiver_mobile'],'price'=>$audit['money'],'reason'=>rtrim($audit['remark'],'||')]);
                $this->success('操作成功','refresh');
            }else{
                // 更新改价记录的退款状态
                Db::name('order_change')->where(['change_id'=>$tmp['change_id']])->update(['pay_status'=>0,'pay_time'=>date('Y-m-d H:i:s'),'pay_no'=>$arr['out_refund_no'],'error'=>$re['msg']]);
                Db::name('order_refund_audit')->where(['audit_id'=>$audit['audit_id']])->update(['audit_status'=>0,'audit_time'=>date('Y-m-d H:i:s')]);
                $this->error('退款失败，请重新提交审核','');
            }
        }else{
        	$sign = true;
        	//循环退款
        	foreach ($list as $k => $v) {

                if ($v['pid']>0) { //补价单退款
                    $pc = Db::name('order_change')->where(['change_id'=>$v['pid']])->find();
                    $arr = [
                        'transaction_id' => $pc['pay_no'],
                        'out_refund_no'  => $audit['audit_id'].'_'.$v['change_id'],
                        'total_fee'      => $pc['price']*100,
                        'refund_fee'     => $v['price']*-100
                    ];
                }else{
                    $arr = [
                        'transaction_id' => $order['pay_no'],
                        'out_refund_no'  => $audit['audit_id'].'_'.$v['change_id'],
                        'total_fee'      => $order['pay_money']*100,
                        'refund_fee'     => $v['price']*-100
                    ];
                }

                Log::record('取消退款'.$order['order_id'],'refund');
                Log::record($arr,'refund');

    	    	$re = $this->refundMoney($arr);

                Log::record($re,'refund');
    	    	if ($re['status']) {
    	    		// 更新改价记录的退款状态
    	    		Db::name('order_change')->where(['change_id'=>$v['change_id']])->update(['pay_status'=>1,'pay_time'=>date('Y-m-d H:i:s'),'pay_no'=>$arr['out_refund_no'],'error'=>null]);
    	    	}else{
    	    		// 更新改价记录的退款状态
    	    		Db::name('order_change')->where(['change_id'=>$v['change_id']])->update(['pay_status'=>0,'pay_time'=>date('Y-m-d H:i:s'),'pay_no'=>$arr['out_refund_no'],'error'=>$re['msg']]);
    	    		$sign=false;
    	    	}
        	}

        	if ($sign) {
        		Db::name('order_refund_audit')->where(['audit_id'=>$audit['audit_id']])->update(['audit_status'=>2,'audit_time'=>date('Y-m-d H:i:s')]);
                $this->sendTmp(['receiver_name'=>$order['receiver_name'],'receiver_mobile'=>$order['receiver_mobile'],'price'=>$audit['money'],'reason'=>rtrim($audit['remark'],'||')]);
    	    	$this->success('操作成功','refresh');
        	}else{
        		Db::name('order_refund_audit')->where(['audit_id'=>$audit['audit_id']])->update(['audit_status'=>1,'audit_time'=>date('Y-m-d H:i:s')]);
    	    	$this->error('部分退款失败，请重新提交审核','');
        	}
        }
    }

    public function refundMoney($order)
    {
    	$cfg = Config::get('pay.wx');
        $PaySdk = new PaySdk($cfg);

        $arr = array(
			'transaction_id' => $order['transaction_id'],
			'out_refund_no'  => $order['out_refund_no'],
			'total_fee'      => $order['total_fee'],
			'refund_fee'     => $order['refund_fee'],
        );

        $re = $PaySdk->submitRefund($arr);

        return $re;
    }

    public function refuse()
    {
        $param = request()->param();
        !$param['id'] && $this->error('参数错误');

        $info = Db::name('order_refund_audit')->where(['audit_id'=>$param['id']])->find();
        if (!in_array($info['audit_status'], [0,1])) { $this->error('本次申请已被处理过，请刷新页面'); }

        Db::name('order_refund_audit')->where(['audit_id'=>$param['id']])->update(['audit_status'=>-1]);
        $this->success('操作成功');
    }

    public function refuselist()
    {
        $iw=Request()->param();

        $start_time=isset($iw['start_time'])?strtotime($iw['start_time']):'';
        $end_time=isset($iw['end_time'])?strtotime($iw['end_time']):'';

        if($end_time){
            $_end_time=getOneDay($end_time);
            // $_end_time=$_end_time['et'];
            if ($end_time==$_end_time['st']) {
                $end_time=$_end_time['et'];
            }
        }else{
            $end_time=getOneDay();
            $end_time=$end_time['et'];
        }

        if ($start_time) {
            // $start_time=getOneDay($start_time);
            // $start_time=$start_time['st'];
        }else{
            $start_time=getDayRegion($end_time,3);
            $start_time=$start_time['st'];
        }
        
        $iw['start_time']=date('Y-m-d H:i:s',$start_time);
        $iw['end_time']=date('Y-m-d H:i:s',$end_time);
        if ($iw['selt']!=='0') {
            $iw['selt']=$iw['selt']?:10;
        }
        
        $Query = Db::field('ora.*,ogr.rg_id')
        ->table('sdzx_order_refund_audit')->alias('ora')
        ->join('sdzx_order_goods_return ogr','ora.audit_id=ogr.audit_id and ogr.rg_status=1','left')
        ->order('ora.audit_time desc')
        ->group('ora.audit_id')
        ->where("(ora.audit_status=2 or ora.audit_status=-1)")
        ->where('ora.audit_time','between',[$iw['start_time'],$iw['end_time']]);

        if ($iw['keywords']) {
            $Query->join('sdzx_order o','ora.order_id=o.order_id','left');
            $Query->where("o.receiver_name like '%{$iw['keywords']}%' or o.receiver_mobile like '%{$iw['keywords']}%'");
        }

        if (isset($iw['status'])) {
            $Query->where("ora.audit_status={$iw['status']}");
        }
        
        $list = $Query->paginate('', false, ['query'=>Request()->param()]);

        $page = $list->render();
        $list = $list->toarray()['data'];
        $return_arr = [];
        foreach ($list as $k => $v) {
            $_time = date('Y-m-d',strtotime($v['audit_time']));

            $v['remark'] = str_replace('||', '<br/>', $v['remark']);
            $v['order'] = Db::name('order')->where(['order_id'=>$v['order_id']])->find();
            if (!isset($return_arr[date('Y-m-d',strtotime($v['audit_time']))]['time'])) {
                $return_arr[$_time]['time'] = $_time;
                $return_arr[$_time]['count'] = Db::field('sum(ora.money) as money')
                ->table('sdzx_order_refund_audit')->alias('ora')
                ->where("(ora.audit_status=2 or ora.audit_status=-1)")
                ->where('ora.audit_time','between',[$iw['start_time'],$iw['end_time']])
                ->value('sum(ora.money)');
            }
            
            $return_arr[$_time]['list'][] = $v;
        }
        $data['w'] = $iw;
        $data['list'] = $return_arr;
        $data['page'] = $page;
        return $this->fetch('',$data);
    }

    public function detail()
    {
        $param = request()->param();
        $order = Db::name('order')->where(['order_id'=>$param['id']])->find();

        $goods = Db::name('order_goods')->where(['order_id'=>$param['id']])->select();

        $refundgoods = Db::table('sdzx_order_goods_return')->alias('gr')
        ->join('sdzx_order_goods og',"gr.specval_id=og.goods_specval_id and og.order_id={$param['id']}")
        ->where(['gr.order_id'=>$param['id']])->select();

        $change = Db::name('order_change')->where(['order_id'=>$param['id']])->select();

        return $this->fetch('',['order'=>$order,'refundgoods'=>$refundgoods,'change'=>$change,'goods'=>$goods]);
    }

    /**
     * 导出审核
     * @return [type] [description]
     */
    public function export(){
        $iw = request()->param();
        $list = Db::field('ora.*,o.*,s.shop_name')
        ->table('sdzx_order_refund_audit')->alias('ora')
        ->join('sdzx_order o','ora.order_id=o.order_id','left')
        ->join('sdzx_shop s','o.user_id=s.user_id','left')
        ->order('ora.audit_time desc')
        ->where("(ora.audit_status=2 or ora.audit_status=-1)")
        ->where('ora.audit_time','between',[$iw['start_time'],$iw['end_time']])
        ->select();

        vendor("PHPExcel.PHPExcel.PHPExcel");
        vendor("PHPExcel.PHPExcel.IOFactory");
        vendor('PHPExcel.PHPExcel.PHPExcel_Style_Alignment');

        $PHPExcel = new \PHPExcel(); //实例化PHPExcel类，类似于在桌面上新建一个Excel表格

        $PHPSheet = $PHPExcel->getActiveSheet(); //获得当前活动sheet的操作对象
        $PHPSheet->setTitle(date('Y-m-d')); //给当前活动sheet设置名称

        $PHPSheet->getColumnDimension('B')->setAutoSize(true);
        $PHPSheet->getColumnDimension('E')->setAutoSize(true);
        $PHPSheet->getColumnDimension('A')->setWidth(20); 

        $PHPSheet->mergeCells('A1:E1');
        $PHPSheet->setCellValue('A1','退款导出');//
        // $PHPSheet->getStyle('A1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $PHPSheet->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $PHPSheet->getStyle('A1')->getFont()->setSize(20)->setBold(true);

        $PHPSheet->mergeCells('A2:E2');
        $PHPSheet->setCellValue('A2','（'.$iw['start_time'].'-'.$iw['end_time'].'）');//
        $PHPSheet->getStyle('A2')->getFont()->setBold(true);
        $PHPSheet->getStyle('A2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);


        $PHPSheet->setCellValue('A3','审核时间')->setCellValue('B3','客户')->setCellValue('C3','金额')->setCellValue('D3','结果')->setCellValue('E3','备注');

        $n = 4;
        foreach ($list as $k => $v) {
            $status = $v['audit_status'] ?'通过':'拒绝';
            $PHPSheet->setCellValue('A'.$n,$v['audit_time'])->setCellValue('B'.$n,$v['receiver_name'].'（'.$v['shop_name']."）".$v['receiver_mobile'])->setCellValue('C'.$n,$v['money'])->setCellValue('D'.$n,$status)->setCellValue('E'.$n,str_replace('||',"\n",$v['remark']));
            $PHPSheet->getStyle('A'.$n)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPSheet->getStyle('B'.$n)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPSheet->getStyle('C'.$n)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPSheet->getStyle('D'.$n)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPSheet->getStyle('E'.$n)->getAlignment()->setWrapText(true);
            $n++;
        }

        $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel,'Excel2007');//按照指定格式生成Excel文件，‘Excel2007’表示生成2007版本的xlsx，‘Excel5’表示生成2003版本Excel文件
        ob_end_clean();
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出07Excel文件
        //header('Content-Type:application/vnd.ms-excel');//告诉浏览器将要输出Excel03版本文件
        header('Content-Disposition: attachment;filename="01simple.xlsx"');//告诉浏览器输出浏览器名称
        header('Cache-Control: max-age=0');//禁止缓存
        $PHPWriter->save("php://output");

    }

    /**
     * 发短信消息
     * 模板内容: 尊敬的${name}，您收到订单退款${price1}元，退款原因：${reason}
     * @param  [type] $order [description]
     * @return [type]        [description]
     */
    function sendTmp($order){
        import('Alidayu.TopSdk');
        import('Alidayu.top.TopClient');
        import('Alidayu.top.request.AlibabaAliqinFcSmsNumSendRequest');
        $appkey="23535194";
        $secret="48953173553ad6ad6b306138f518d7f1";

        $c = new \TopClient();
        $c ->appkey = $appkey ;
        $c ->secretKey = $secret ;
        $req = new \AlibabaAliqinFcSmsNumSendRequest();
        $req ->setExtend( "" );
        $req ->setSmsType( "normal" );
        $req ->setSmsFreeSignName( "速冻在线" );
        $req ->setSmsParam("{name:'".$order['receiver_name']."',price1:'".$order['price']."',reason:'".$order['reason']."'}");
        $req ->setRecNum( $order['receiver_mobile'] );
        $req ->setSmsTemplateCode( "SMS_112220006" );
        $re = $c ->execute( $req );
    }
}